#include "StdAfx.h"
#include "ExporterSTL.h"
#include "ExporterFactory.h"
#include "AnyDocument.h"
#include "AnyView.h"

#include <TDF_ChildIterator.hxx> 
#include <TNaming_Tool.hxx> 
#include <StlAPI_Writer.hxx>
#include <TopoDS_Compound.hxx>
#include <BRep_Builder.hxx>

#pragma  comment(lib, "TKStl.lib")

REGISTERE_FILEEXPORTER(CExporterSTL, STL_EXPORTER_GUID);

CExporterSTL::CExporterSTL(void)
{
	m_ExportInfo.szDescription = _T("STL Files (*.stl)|*.stl||");
	m_ExportInfo.szFileExt = _T(".stl");
}

CExporterSTL::~CExporterSTL(void)
{
}

bool CExporterSTL::Export()
{
	CAnyDocument* pAnyDoc = m_ExportInfo.GetDocument();
	CAnyView* pAnyView = m_ExportInfo.GetView();

	if( NULL == pAnyDoc || NULL == pAnyView)
		return false;

	Handle_TDocStd_Document hDoc = pAnyDoc->GetStdDoc();
	TDF_Label labelRoot = hDoc->Main();

	TopoDS_Compound RES;
	BRep_Builder MKCP;
	MKCP.MakeCompound(RES);

	int nCount = 0;
	TDF_ChildIterator it(labelRoot);
	for(; it.More(); it.Next(), ++nCount)
	{
		
		TDF_Label subLabel = it.Value();
		Handle_TNaming_NamedShape  namedShape;
		if(!subLabel.FindAttribute(TNaming_NamedShape::GetID(), namedShape))
			continue;

		TopoDS_Shape shape = TNaming_Tool::GetShape(namedShape);
		if(shape.IsNull())
			continue;

		MKCP.Add(RES, shape);
	}

	if(nCount == 0)
		return false;

	StlAPI_Writer myStlWriter;
	Standard_CString szFile = m_ExportInfo.szFullPath.GetBuffer();
	myStlWriter.Write(RES, szFile);
	
	return true;
}